//
//  LoginViewController.m
//  Growth
//
//  Created by Hobo.Chen on 12/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import"RegistViewController.h"
#import "WebRequest.h"
#import "WebConnetionArray.h"

#import "NotificationEngine.h"

#import "GrowthAppDelegate.h"


#import "CJSONSerializer.h"
#import "WebRequest.h"
#import "WebConnection.h"
#import "ASIHTTPConnection.h"

#import "PhoneRegisterViewController.h"

static WebConnection *loginConnection;

static WebConnectionArray *timeline_Connection;

static WebConnectionArray *createNewUser_Connection;

static WebConnectionArray *bindUser_Connection;

static ASIHTTPConnection *login_connect;

@interface LoginViewController (Private)


@end


@implementation LoginViewController

@synthesize delegate;

@synthesize loginIDtextField;
@synthesize loginkeytextField;

@synthesize  oauthType;
@synthesize qq_userInfo_dict;

@synthesize weiBoEngine;

@synthesize weibo_userInfo_dict;

@synthesize backGroundButton;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewWillAppear:(BOOL)animated{
    
    
    [self navigationBarInit];
    [super viewWillAppear:YES];
    
    
}

- (void)viewDidLoad {
    
    self.navigationItem.title = @"登录";
    
    self.navigationController.navigationBar.hidden = YES;
    
    [self.view setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    
    UIView *nilView = [[UIView alloc] init];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:nilView];
    [nilView release];
    [self.navigationItem setLeftBarButtonItem:leftButtonItem];
    [leftButtonItem release];
    
    CGRect frame1 = loginIDtextField.frame;
    frame1.size.height = 40;
    [loginIDtextField setFrame:frame1];
    
    frame1 = loginkeytextField.frame;
    frame1.size.height  = 40;
    [loginkeytextField setFrame:frame1];
    
    //ios7 优化
    if( iOS7) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
       // [self.navigationController.navigationBar setBarTintColor:BarTintColor];
        self.navigationController.navigationBar.translucent = NO;
    }
    else{
        
       // [self.navigationController.navigationBar setBarTintColor:BarTintColor];
    }

    
    oauthType = 0;  //非第三方登陆
    //显示上一次登陆的账号
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"email"]) {
        loginIDtextField.text=[[NSUserDefaults standardUserDefaults] valueForKey:@"email"];
        self.loginIDtextField.textColor = [UIColor blackColor];
    }
    
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"login_bg.png" ofType:nil];
    BGimageView.image = [UIImage  imageWithContentsOfFile:path];
    
    if (iPhone5) {
        CGRect frame = BGimageView.frame;
        frame.size.height = 568;
        BGimageView.frame = frame;
    }
    
       [backGroundButton setShowsTouchWhenHighlighted:NO];
       [backGroundButton setTintColor:[UIColor whiteColor]];
     
        backGroundButton.backgroundColor = [UIColor clearColor]; 

    
       [super viewDidLoad];
}



#pragma mark --
#pragma mark 用第三方建新账号

-(void)createNewQQUser:(NSString *)nickName{ 
    
    if (self.oauthType == 2) { //qq
        
        NSString *userName = nickName;
        NSString *userPhoto = [self.qq_userInfo_dict objectForKey:@"figureurl_2"];
        NSString *gender = [self.qq_userInfo_dict objectForKey:@"gender"];
        
        CLog(@"qq_usrinfoDict %@", qq_userInfo_dict);
        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"platformId\":%d,\"accessToken\":\"%@\",\"nickname\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\"}",self.oauthType,_tencentOAuth.openId,userName,userPhoto,gender];
        
        
        //   NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest registBindingNewWith:_jsonData];
        CLog(@"request %@", request_derectIn);
        if (createNewUser_Connection != nil) {
            createNewUser_Connection.connectionDelegate = nil;
        }
        createNewUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];

    }
    
    if (self.oauthType == 1) { //weibo
        
        NSString *userName = nickName;

        NSString *userPhoto = [self.weibo_userInfo_dict objectForKey:@"profile_image_url"];
        NSString *gender = [self.weibo_userInfo_dict objectForKey:@"gender"];
        
        CLog(@"qq_usrinfoDict %@", weibo_userInfo_dict);
        NSString *token = [self.weibo_userInfo_dict objectForKey:@"id"];

        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"platformId\":%d,\"accessToken\":\"%@\",\"nickname\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\"}",self.oauthType,token,userName,userPhoto,gender];
        
        
        //   NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
       
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest registBindingNewWith:_jsonData];
        CLog(@"request %@", request_derectIn);
        if (createNewUser_Connection != nil) {
            createNewUser_Connection.connectionDelegate = nil;
        }
       createNewUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];

    }
       

    
}



#pragma mark --
#pragma mark 第三方绑定已有账号

-(void)bindQQUser:(NSString *)email key:(NSString *)pass{
    
    if (self.oauthType == 2) { //qq
        
        NSString *userName = [self.qq_userInfo_dict objectForKey:@"nickname"];
        NSString *userPhoto = [self.qq_userInfo_dict objectForKey:@"figureurl_2"];
        NSString *gender = [self.qq_userInfo_dict objectForKey:@"gender"];
       
        CLog(@"qq_usrinfoDict %@", qq_userInfo_dict);
        NSString *openId= _tencentOAuth.openId;
        
   NSString *theBodyString = [NSString stringWithFormat:@"{\"bindingType\":\"%@\",\"appId\":%d,\"token\":\"%@\",\"nickname\":\"%@\",\"platform\":\"%@\",\"account\":\"%@\",\"password\":\"%@\"}",@"exist",1,openId,userName,@"qq",email,pass];        
        
        CLog(@"theBodyString  %@", theBodyString);
        
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest userBindingWith:_jsonData];
        CLog(@"request %@", request_derectIn);
        if (bindUser_Connection != nil) {
            bindUser_Connection.connectionDelegate = nil;
        }
        bindUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];
        

        
    }
    if (self.oauthType ==1) { //weibo
        
        NSString *userName = [self.weibo_userInfo_dict objectForKey:@"name"];
        NSString *userPhoto = [self.weibo_userInfo_dict objectForKey:@"profile_image_url"];
        NSString *gender = [self.weibo_userInfo_dict objectForKey:@"gender"];
        
        CLog(@"qq_usrinfoDict %@", weibo_userInfo_dict);
        NSString *token = [self.weibo_userInfo_dict objectForKey:@"id"];
        
        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"bindingType\":\"%@\",\"appId\":%d,\"token\":\"%@\",\"nickname\":\"%@\",\"platform\":\"%@\",\"account\":\"%@\",\"password\":\"%@\"}",@"exist",1,token,userName,@"sina",email,pass];        
        
        
        
        CLog(@"theBodyString  %@", theBodyString);
        
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest userBindingWith:_jsonData];
        CLog(@"request %@", request_derectIn);
        if (bindUser_Connection != nil) {
            bindUser_Connection.connectionDelegate = nil;
        }
       bindUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];
        

        
    }
    
      
}



#pragma mark 绑定页面

-(void)loadThirdPartView{
    
    if (self.oauthType == 1) { //sina weibo
        
  
        ThirdPartLoginViewController *viewController = [[ThirdPartLoginViewController alloc] initWithUserInfo:weibo_userInfo_dict platformId:1];
        viewController.delegate = self;
        viewController.pushViewDelegate = self;
        [self.navigationController pushViewController:viewController animated:YES];
        
        [viewController release];
        
    }
    
    else if(self.oauthType == 2){ //qq
        
        ThirdPartLoginViewController *viewController = [[ThirdPartLoginViewController alloc] initWithUserInfo:qq_userInfo_dict platformId:2];
        viewController.delegate = self;
        viewController.pushViewDelegate = self;
        [self.navigationController pushViewController:viewController animated:YES];
        
        [viewController release];
        
    }
    
    
}



#pragma mark -
#pragma mark 手机、邮箱注册
-(IBAction)registerNowActon{

    RegistViewController *registViewController = [[RegistViewController alloc] init];
    
    [self.navigationController pushViewController:registViewController animated:YES];
    
    [registViewController release];
}



- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) { //手机注册
        
        PhoneRegisterViewController *content = [[PhoneRegisterViewController alloc] init];
        [self.navigationController pushViewController:content animated:YES];
        [content release];
                      
    }
    else if(buttonIndex == 1){ // 邮箱注册
            
        RegistViewController *registViewController = [[RegistViewController alloc] init];
            
        [self.navigationController pushViewController:registViewController animated:YES];
        
        [registViewController release];
  
    }
    
    
    [actionSheet release];
} 




#pragma mark textField delegate

-(IBAction)backgroundTap:(id)sender{
    
    [loginIDtextField resignFirstResponder];
    [loginkeytextField resignFirstResponder];
    
}

#pragma mark load data
//下载可管理的时间轴

-(void)loadTimelineMember:(int)uid{
    
    [LoadingView showDefaultLoadingView];
    
    NSMutableURLRequest * request = [WebRequest userTiemlineMemberRequestWith:[NSString stringWithFormat:@"%d",uid]];
	
	CLog(@"request %@", request);
    if (timeline_Connection != nil) {
        timeline_Connection.connectionDelegate = nil;
    }
	timeline_Connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:@"TimelineId"];
    
}


#pragma mark -WebConnection delegate

- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    
    
    [LoadingView hideWithAnimated:YES];
      
    NSDictionary *dictionary = [dict objectForKey:@"object"];
   
    CLog(@"url %@", url);
    
        
    //三方 新用户绑定
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/user/binding",UCENTERBASEURL]]) {//返回 token userid
        
        NSInteger errorCode = [[dictionary objectForKey:@"errorCode"] intValue];
        
        //save usre info
        if((errorCode == 0 || errorCode == 6) &&[[dictionary allKeys] containsObject:@"userId"]){
            
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userNickname"] forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
        
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"Ucenter-Code"] forKey:@"Ucenter-Code"];
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"Ucenter-VerifyCode"] forKey:@"Ucenter-VerifyCode"];
                
            [self  loginSuccess];
        
            }
        else{
            
            NSString *errorReason = [dictionary objectForKey:@"errorReason"];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:errorReason 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            [alert release];
            
        }
        
        return;
        
    }
    
    
  
    //可管理时间轴
    
    
}

- (void)connectionArrayError:(NSError *)error{
	    

     [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME];
   
    self.view.userInteractionEnabled=YES;
   // [self loginError];
        
}



- (void)connectionSuccess:(NSDictionary *)dict{
	
	[LoadingView hideWithAnimated:YES];
    CLog(@"login return data = %@",dict);
    
           
        if(dict){
            
            NSDictionary *loginDict = [[dict objectForKey:@"datalist"] objectAtIndex:0];
            
            NSInteger errorCode = [[dict objectForKey:@"isSuccess"] intValue];
            
            //save usre info
            if( errorCode == 1 ){
                getUserIdSucced = YES;
                [[NSUserDefaults standardUserDefaults] setValue:[loginDict objectForKey:@"UserID"] forKey:USER_ID];
                [[NSUserDefaults standardUserDefaults]setValue:[loginDict objectForKey:@"NickName"] forKey:@"nickName"];
                [[NSUserDefaults standardUserDefaults]setValue:[loginDict objectForKey:@"UserRankType"] forKey:@"userType"];
                
                [[NSUserDefaults standardUserDefaults] setValue:[loginDict objectForKey:@"userAccountStatus"] forKey:@"userAccountStatus"];
               
                [self  userLoginSuccess];
            }
            else {
                
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败!" message:@"帐号密码错误！" 
                                                               delegate:self 
                                                      cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                [alert release];
                
                return;
            }
            
        }
        
        else{
            
            [self loginError];
           
            return;
        }
        
  
    
}

- (void)connectionError:(NSError *)error{
	CLog(@"error info");
   [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2]; 
    self.view.userInteractionEnabled=YES;
       
}
- (void)postSuccess:(NSString *)postinfo{
    
}

#pragma mark ***********************/

- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
     CLog(@"dict = %@",dict);
    [LoadingView hideWithAnimated:YES];
    
    if (dict && [[dict objectForKey:@"isSuccess"] boolValue]) {
        
        NSDictionary *userDict = [[dict objectForKey:@"datalist"] objectAtIndex:0];
        [[NSUserDefaults standardUserDefaults] setValue:[userDict objectForKey:@"UserID"] forKey:USER_ID];
        [[NSUserDefaults standardUserDefaults] setValue:[userDict objectForKey:@"UserName"] forKey:USER_NAME];
        [[NSUserDefaults standardUserDefaults] setValue:loginkeytextField.text forKey:USER_KEY];
        
        [[NSUserDefaults standardUserDefaults] setValue:[userDict objectForKey:@"UserType"] forKey:ROLE];
        [[NSUserDefaults standardUserDefaults] setValue:[userDict objectForKey:@"CompanyName"] forKey:COMPANYNAME];
        [self userLoginSuccess];
    }
    else{
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"%@",[dict objectForKey:@"messageContent"]]
        
                                                           delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [alert show];
            [alert release];

    }
    
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"返回的数据" message:[NSString stringWithFormat:@"%@",dict]
//                          
//                                                   delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil];
//    [alert show];
//    [alert release];
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    [LoadingView hideWithAnimated:YES];
    CLog(@"erro = %@",error);
    
}


#pragma mark 登陆Action

-(IBAction)loginAction{
 
    //test
    
    if (loginIDtextField.text == nil || loginIDtextField.text.length == 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"用户名不能为空"
							  
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
		[alert show];
        [alert release];
        return;

    }
    if (loginkeytextField.text == nil || loginkeytextField.text.length == 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"密码不能为空"
							  
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
		[alert show];
        [alert release];
        return;
        
    }

    
    
  
    [LoadingView showDefaultLoadingView];
   
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileUser/MobileLoginAction.aspx",BASEURL];
    
    CLog(@"url = %@",urlString);
    
	NSURL *url = [NSURL URLWithString:urlString];
    
    
    NSArray *keys = [NSArray arrayWithObjects:@"UserName",@"Password", nil];
    
   NSArray *objects = [NSArray arrayWithObjects:loginIDtextField.text,loginkeytextField.text, nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
    
    //  //
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (login_connect != nil) {
        login_connect.connectionDelegate = nil;
        [login_connect release];
        login_connect = nil;
    }
    login_connect = [[ASIHTTPConnection alloc] initPOSTWithURL:url jsonData:_jsonData];
    login_connect.connectionDelegate = self;
    
    [login_connect startAsynchronous];
    
    [self backgroundTap:nil];
    
}


#pragma mark qq 三方登陆 begin

-(IBAction)QQLoginAction{
    
    self.oauthType =   2; //qq login
    
    _permissions =  [[NSArray arrayWithObjects:
					  @"get_user_info",@"add_share", @"add_topic",@"add_one_blog", @"list_album", 
					  @"upload_pic",@"list_photo", @"add_album", @"check_page_fans",nil] retain];
	
	
	_tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQAPPKey
											andDelegate:self];
	_tencentOAuth.redirectURI = @"www.qq.com";
    
    _tencentOAuth.accessToken = [[NSUserDefaults standardUserDefaults] valueForKey:QQAccessToken];
    _tencentOAuth.expirationDate = [[NSUserDefaults standardUserDefaults] valueForKey:QQExpirationDate];
    _tencentOAuth.openId = [[NSUserDefaults standardUserDefaults] valueForKey:QQOpenId];
    [_tencentOAuth authorize:_permissions inSafari:NO];
    
}


/**
 * Called when the user successfully logged in.
 */
- (void)tencentDidLogin {
	// 登录成功
#pragma mark HOBO
    //在这里直接调用UserInfo即可获取用户信息
    [LoadingView showDefaultLoadingView];
    [self onClickGetUserInfo];
    
		
	
}


- (void)onClickGetUserInfo {

	[_tencentOAuth getUserInfo];
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
	[LoadingView hideWithAnimated:NO];	
}

/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
	[LoadingView hideWithAnimated:NO];
}
/**
 * Called when the get_user_info has response.
 */
- (void)getUserInfoResponse:(APIResponse*) response {
    
#pragma mark HOBO
    //这里是获取用户信息成功的用户信息
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
		
		NSMutableString *str=[NSMutableString stringWithFormat:@""];		
		for (id key in response.jsonResponse) {			
			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
		}
        
        self.qq_userInfo_dict = response.jsonResponse;
        
           
    //直接用login 接口 验证
        NSArray *keys = [NSArray arrayWithObjects:@"loginType", @"appId",@"platform",@"token",@"osType", nil];
        
        
        NSArray *objects = [NSArray arrayWithObjects:@"qq",[NSNumber numberWithInt:1],@"qq",_tencentOAuth.openId, @"ios", nil];
        NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
        
        NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        //   	
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        //	
        NSMutableURLRequest * request = [WebRequest LoginRequestWith:_jsonData];
        CLog(@"request %@", request);
        if (loginConnection != nil) {
            loginConnection.connectionDelegate = nil;
        }
        
        [LoadingView showDefaultLoadingView];   
        loginConnection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
      	
        
	}
	else {

	}
	
    
    [[NSUserDefaults standardUserDefaults] setValue:_tencentOAuth.accessToken forKey:QQAccessToken];
    [[NSUserDefaults standardUserDefaults] setValue:_tencentOAuth.expirationDate forKey:QQExpirationDate];
    [[NSUserDefaults standardUserDefaults] setValue:_tencentOAuth.openId forKey:QQOpenId];
    
    NSLog(@"AccessToken %@", _tencentOAuth.accessToken);
    NSLog(@"ExpirationDate %@", _tencentOAuth.expirationDate);
    NSLog(@"OpenId %@", _tencentOAuth.openId);
}

/**
 * Called when the add_share has response.
 */
- (void)addShareResponse:(APIResponse*) response {
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
		
		NSMutableString *str=[NSMutableString stringWithFormat:@""];		
		for (id key in response.jsonResponse) {			
			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
		}
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作成功" message:[NSString stringWithFormat:@"%@",str]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles:nil];
		[alert show];
		
		
		
	}
	else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%", response.errorMsg]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];
	}
	
	
	
}





///////////////////////////////////////////////////////////////////////////////////////////////////

//TencentRequestDelegate

/**
 * Handle the auth.ExpireSession api call failure
 */
- (void)request:(TencentRequest*)request didFailWithError:(NSError*)error{
	//NSString *errorInfo = [error localizedDescription];
	NSLog(@"Failed to expire the session");
}

- (void)request:(TencentRequest *)request didReceiveResponse:(NSURLResponse *)response {
	NSLog(@"received response");
}



/**
 * Called when a request returns and its response has been parsed into
 * an object. The resulting object may be a dictionary, an array, a string,
 * or a number, depending on the format of the API response. If you need access
 * to the raw response, use:
 *
 * (void)request:(FBRequest *)request
 *      didReceiveResponse:(NSURLResponse *)response
 */
- (void)request:(TencentRequest *)request didLoad:(id)result dat:(NSData *)data{
	if ([result isKindOfClass:[NSDictionary class]]) {
		NSDictionary *root = (NSDictionary *)result;
		if ([[root allKeys] count] == 0) {
			NSLog(@"received didLoad error");
			return;
		}
	}
};


#pragma mark
#pragma  mark sina微博登陆

-(IBAction)SinaLoginAction{

    self.oauthType = 1;
    WBEngine *engine = [[WBEngine alloc] initWithAppKey:kWBSDKDemoAppKey appSecret:kWBSDKDemoAppSecret];
    [engine setRootViewController:self];
    [engine setDelegate:self];
    //[engine setRedirectURI:@"http://"];
    [engine setRedirectURI:@"http://www.lanbaoo.com"];
    [engine setIsUserExclusive:NO];
    self.weiBoEngine = engine;
    [engine release];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];

    [weiBoEngine logIn];
    
}


- (void)engineDidLogIn:(WBEngine *)engine
{
  
    //微博登陆成功
    //取用户信息
    
    NSLog(@"UID Did Login %@", weiBoEngine.userID);
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:weiBoEngine.userID forKey:@"uid"];
    
    [LoadingView showDefaultLoadingView];
    
    [weiBoEngine loadRequestWithMethodName:@"users/show.json"
                                httpMethod:@"GET"
                                    params:dict
                              postDataType:kWBRequestPostDataTypeNormal
                          httpHeaderFields:nil];

    
}

#pragma mark - UIAlertViewDelegate Methods

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == kWBAlertViewLogInTag)
    {
        
        //取用户信息
        
        NSLog(@"UID Did Login %@", weiBoEngine.userID);
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setValue:weiBoEngine.userID forKey:@"uid"];
        
        [weiBoEngine loadRequestWithMethodName:@"users/show.json"
                                    httpMethod:@"GET"
                                        params:dict
                                  postDataType:kWBRequestPostDataTypeNormal
                              httpHeaderFields:nil];
        
        return;

        
        
    }
    else if (alertView.tag == kWBAlertViewLogOutTag)
    {
       
    }
}

- (void)engine:(WBEngine *)engine didFailToLogInWithError:(NSError *)error
{
   
  
    UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:nil 
													   message:@"登录失败！" 
													  delegate:nil
											 cancelButtonTitle:@"确定" 
											 otherButtonTitles:nil];
	[alertView show];
	[alertView release];
}



#pragma mark - WBEngineDelegate Methods

//user info
- (void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result
{
    
    //NSLog(@"requestDidSucceedWithResult: %@", result);
    if ([result isKindOfClass:[NSDictionary class]])
    {
        NSLog(@"User Info %@", result);
        
        self.weibo_userInfo_dict = result;
     
        //直接用login 接口
         NSString *weibo_token = [weibo_userInfo_dict objectForKey:@"id"];
        
        NSArray *keys = [NSArray arrayWithObjects:@"loginType", @"appId",@"platform",@"token",@"osType", nil];
        
        
        NSArray *objects = [NSArray arrayWithObjects:@"sina",[NSNumber numberWithInt:1],@"sina",weibo_token, @"ios", nil];

        
        
        NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
        
        NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        //   	
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        //	
        NSMutableURLRequest * request = [WebRequest LoginRequestWith:_jsonData];
        CLog(@"request %@", request);
        if (loginConnection != nil) {
            loginConnection.connectionDelegate = nil;
        }
        
        [LoadingView showDefaultLoadingView];
        
        loginConnection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
      	
        
    }
}

- (void)engine:(WBEngine *)engine requestDidFailWithError:(NSError *)error
{
    [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"微博登陆错误，请重试！"];
    NSLog(@"requestDidFailWithError: %@", error);
}


-(void)dealloc{
    
    if (login_connect != nil) {
        login_connect.connectionDelegate = nil;
        [login_connect release];
        login_connect = nil;
    }
    
    [backGroundButton release];
    
    if (loginConnection != nil) {
        loginConnection.connectionDelegate = nil;
        [loginConnection release];
        loginConnection = nil;
    }
    
    if (timeline_Connection != nil) {
        timeline_Connection.connectionDelegate = nil;
        [timeline_Connection release];
        timeline_Connection = nil;
    }
    
    
    if (createNewUser_Connection != nil) {
        createNewUser_Connection.connectionDelegate = nil;
        [createNewUser_Connection release];
        createNewUser_Connection = nil;
    }
    
    if (bindUser_Connection != nil) {
        bindUser_Connection.connectionDelegate = nil;
        [bindUser_Connection release];
        bindUser_Connection = nil;
    }
    
    [BGimageView release];
    BGimageView = nil;
    
    [myscrollView release];
    myscrollView = nil;
    
    [loginIDtextField release];
    [loginkeytextField release];
    [qq_userInfo_dict release];
    [weiBoEngine release];
    [weibo_userInfo_dict release];
    [super dealloc];
    
}


#pragma mark textField delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField == loginIDtextField) {
        [loginkeytextField becomeFirstResponder];
    }
    else{
         [textField resignFirstResponder];
        [self loginAction];
    }
    
    
    
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    if (textField == loginIDtextField) {
        
        [myscrollView setContentSize:CGSizeMake(320, 600)];
        [myscrollView setContentOffset:CGPointMake(0, 150) animated:YES];
    }
   
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (textField == loginkeytextField) {
        
        [myscrollView setContentSize:CGSizeMake(320, 560)];
        [myscrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        [textField resignFirstResponder];
    }
   
    
}

#pragma mark action 获取到用户信息操作

- (void)loginSuccess{
    
    
    CLog(@"Login success!");
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] != nil) {
        
        [[NotificationEngine sharedNotificationEngine] postDeviceToken];
        
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:REGIST_LOGIN_KEY];
        int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
        
        NSString *loginType;
        switch (oauthType) {
            case 0:
            {
                loginType = @"meetstudio";
                break;
            }
            case 1:
            {
                loginType = @"sina";
                break;
            }
            case 2:
            {
                loginType = @"qq";
                break;
            }
            default:
                break;
        }
        NSString *uidStr = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] stringValue];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:uidStr, @"uid", loginType, @"type", nil];
        
        [MobClick event:MobClick_Login attributes:dict];
        
        [self loadTimelineMember:uid];
        
    }   
    else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"帐号密码错误！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        
    }
    
    
}

- (void)loginErrorWith:(NSString *)info
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败!" message:@"连接错误，重新连接！" 
                                                   delegate:self 
                                          cancelButtonTitle:@"取消" otherButtonTitles:nil];
    
    [alert show];
    [alert release];
    
}

- (void)loginError{
    
	[self loginErrorWith:@"密码错误或网络连接失败！"];
}




#pragma mark - User loggin success  登陆成功，到内容页面
- (void)userLoginSuccess{
    
       
    if ([[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] != nil) {
      
        [self.navigationController dismissModalViewControllerAnimated:YES];
        
        
    }
    
    
}




#pragma mark -
#pragma mark UINavigateBar
- (void)navigationBarInit
{
          
   
    
}

@end
